package com.yu.app.controller;

import com.yu.app.pojo.dto.UserDTO;
import com.yu.app.pojo.form.LoginByWeixinForm;
import com.yu.app.pojo.form.UpdateUserForm;
import com.yu.app.service.impl.UserServiceImpl;
import com.yu.app.common.annotation.NeedLogin;
import com.yu.common.exception.ServiceException;
import com.yu.common.util.jwt.JWTUtil;
import com.yu.common.util.result.R;
import com.yu.app.common.util.session.SessionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Api(tags = "用户服务")
@RestController
@Slf4j
@RequestMapping("/api-app/user")
public class UserController {
    @Resource
    private UserServiceImpl userService;
    @Value("${spring.profiles.active}")
    private String runEnvironment; // 运行环境，用于开发时测试用

    // TODO
    @ApiOperation("开发测试时开发的登录接口")
    @PostMapping("/login/dev")
    public R<UserDTO> login() throws Exception {
        // 测试开发环境，必须事先到数据库里面去插入wxOpenid=0的数据
        if ("dev".equalsIgnoreCase(runEnvironment)) {
            UserDTO userDTO = userService.getUserDTO("0");
            SessionUtil.setUserSession(userDTO);
            log.info("[开发环境，用户登录] {}", userDTO);
            return R.ok(userDTO);
        }
        return R.fail("不是开发环境");
    }

    @ApiOperation("通过微信登录")
    @PostMapping("/login/weixin")
    public R<UserDTO> loginByWx(@RequestBody LoginByWeixinForm form) throws Exception {
        return R.ok(userService.loginByWeixin(form));
    }

    @ApiOperation("退出登录")
    @DeleteMapping("/logout")
    public R logout() throws ServiceException {
        userService.logout(SessionUtil.getToken());
        return R.ok();
    }

    @ApiOperation("根据token获取用户数据")
    @NeedLogin
    @GetMapping("/info")
    public R<UserDTO> getUserInfo() throws ServiceException {
        String token = SessionUtil.getToken();
        UserDTO userInfo = userService.getUserDTO(JWTUtil.getWxOpenid(token));
        userInfo.setToken(token);
        SessionUtil.updateUserSession(token); // 延长token的过期时间
        return R.ok(userInfo);
    }

    @ApiOperation("更新信息")
    @NeedLogin
    @PutMapping("")
    public R updateUser(@ApiParam("更新学生信息表单") @RequestBody UpdateUserForm form) throws Exception {
        return R.ok(userService.updateUser(form));
    }


}
